<template>
  <div class="functionalAuthority">
    <div class="topBox" :class="{ hid: !menuData }">
      <div class="treeMenuRight" v-if="menuData">
        <div class="menuCurr" v-if="childFlag">
          <p>
            <span>上级权限ID：</span><span>{{
              menuData.parentId == -1 ? "没有上级菜单" : menuData.parentId
            }}</span>
          </p>
          <p>
            <span>权限ID：</span><span>{{ menuData.id }}</span>
          </p>
          <p>
            <span>权限级别：</span><span>{{ menuData.menuLevel }}</span>
          </p>
          <p>
            <span>权限名称：</span><span><Input v-model="menuData.title" placeholder="请输入权限名字"
                style="width: 220px" /></span>
          </p>

          <div class="menuBtn">
            <Button type="primary" @click="createChildMenu">创建子权限</Button>
            <Button type="success" @click="permissionUpdate">保存</Button>
            <Button type="warning" @click="permissionDelete">删除</Button>
          </div>
        </div>
        <div class="menuCurr" v-if="!childFlag">
          <p>
            <span>上级权限ID：</span><span>{{ menuData.id }}</span>
          </p>
          <p>
            <span>权限名称：</span><span><Input v-model="createMenuName" placeholder="请输入权限名字"
                style="width: 220px" /></span>
          </p>
          <div class="menuBtn">
            <Button type="text" @click="createMenuNameCancel">取消</Button>
            <Button type="success" @click="permissionSave">保存</Button>
          </div>
        </div>
      </div>
    </div>
    <div class="treeMenu" ref="TableHeight" :style="{ height: onresizeHeight + 'px' }">
      <Row>
        <Col :xs="2" :sm="4" :md="6" :lg="8" class="treeMenuLeft">
        <Tree :data="data1" @on-select-change="treeSelChange"></Tree>
        </Col>
        <Col :xs="20" :sm="16" :md="12" :lg="8">
        <Tree :data="data2" show-checkbox check-strictly check-directly
          @on-check-change="pcSelChange"></Tree>
        </Col>
        <Col :xs="2" :sm="4" :md="6" :lg="8">
        <Tree :data="data3" show-checkbox check-strictly check-directly
          @on-check-change="appSelChange"></Tree>
        </Col>
      </Row>
    </div>
  </div>
</template>

<script>
  import jurisdictionMgr from '@/biz/jurisdiction/jurisdiction'


  export default {
    name: 'functionalAuthority',
    data() {
      return {
        onresizeHeight: '',
        childFlag: true,
        TabVal: 'name1',
        menuData: '',
        createMenuName: '',
        data1: [],
        data2: [],
        data3: [],

        webMenuList: [],
        appMenuList: [],
        userId: JSON.parse(this.$tool.getStorage('userMess')).userId,
      }
    },

    mounted() {
      window.onresize = () => {
        return (() => {
          setTimeout(() => {
            this.onresizeHeight =
              window.innerHeight - this.$refs.TableHeight.offsetTop - 50
          }, 10)
        })()
      }
    },
    methods: {
      pcSelChange(val) {
        this.webMenuList = []
        val.forEach((item) => {
          this.webMenuList.push(item.id)
        })
      },
      appSelChange(val) {
        this.appMenuList = []

        val.forEach((item) => {
          this.appMenuList.push(item.id)
        })
      },
      treeSelChange(val) {
        let vv = this.$tool.deepClone(val)
        this.childFlag = true
        if (vv && vv.length) {
          this.menuData = vv[0]
        } else {
          this.menuData = ''
        }
        this.ergodicId()
      },
      createChildMenu() {
        if (this.menuData.menuLevel > 4) {
          this.$Message.warning('菜单最大为5级。')
        } else {
          this.childFlag = false
        }
      },
      createMenuNameCancel() {
        this.childFlag = true
        this.createMenuName = ''
      },
      tabValChange(val) {},

      // 权限树数据
      getPermissionMenuList() {
        jurisdictionMgr
          .permissionMenuList()
          .then((res) => {
            this.data1 = res
          })
          .catch((err) => {})
      },
      //建权限
      permissionSave() {
        let params = {
          id: this.menuData.id, //上级菜单id
          title: this.createMenuName, //菜单名称
          userId: this.userId,
        }
        jurisdictionMgr
          .permissionMenuSave(params)
          .then((res) => {
            this.$Message.success('菜单创建成功')
            this.menuData = ''
            this.createMenuNameCancel()
            this.getPermissionMenuList()
            this.getFunctionMenuList()
            // this.ergodicId()
          })
          .catch((err) => {})
      },

      permissionBind() {
        let params = {
          id: this.menuData.id, //#权限id
          webMenuList: this.webMenuList, //#后台菜单id集合
          appMenuList: this.appMenuList, //#APP菜单id集合
          userId: this.userId,
        }
        jurisdictionMgr
          .permissionMenuBind(params)
          .then((res) => {
            this.$Message.success('菜单保存成功')
            this.createMenuNameCancel()
            this.getPermissionMenuList()
            this.getFunctionMenuList()
            this.menuData = ''
            // this.ergodicId()
          })
          .catch((err) => {})
      },
      // 修改权限
      permissionUpdate() {
        let params = {
          id: this.menuData.id,
          title: this.menuData.title, //菜单名称
          userId: this.userId,
        }
        jurisdictionMgr
          .permissionMenuUpdate(params)
          .then((res) => {
            this.permissionBind()
          })
          .catch((err) => {})
      },
      permissionDelete() {
        this.$Modal.confirm({
          title: '删除菜单',
          content: `<p>确定删除菜单“${this.menuData.title}”？</p>`,
          onOk: () => {
            let params = {
              id: this.menuData.id,
              userId: this.userId,
            }
            jurisdictionMgr
              .permissionMenuDelete(params)
              .then((res) => {
                this.$Message.success('菜单删除成功')
                this.createMenuNameCancel()
                this.getPermissionMenuList()
                this.menuData = ''
              })
              .catch((err) => {
                this.$Message.error(err)
              })
          },
          onCancel: () => {
            this.$Message.info('你取消了删除。')
          },
        })
      },

      //初始化菜单数据
      getFunctionMenuList() {
        this.getFunctionMenuList1().then(() => {
          this.getFunctionMenuList2()
        })
      },
      getFunctionMenuList1() {
        let params = {
          menuItem: '1',
        }
        return new Promise((resolve, reject) => {
          jurisdictionMgr
            .functionMenuList(params)
            .then((res) => {
              this.data2 = res
              resolve()
            })
            .catch((err) => {})
        })
      },

      getFunctionMenuList2() {
        let params1 = {
          menuItem: '2',
        }
        jurisdictionMgr
          .functionMenuList2(params1)
          .then((res) => {
            this.data3 = res
          })
          .catch((err) => {})
      },

      // 递归遍历勾选上的id合集
      ergodicId() {
        let params = {
          id: this.menuData.id,
        }
        jurisdictionMgr
          .bindFunctionMenuById(this.menuData.id ? params : '')
          .then((res) => {
            this.webMenuList = this.$tool.deepClone(res.webMenuIds)
            this.appMenuList = this.$tool.deepClone(res.appMenuIds)
            this.recursionTree(this.data2, res.webMenuIds)
            this.recursionTree(this.data3, res.appMenuIds)
          })
          .catch((err) => {
            this.recursionTree(this.data2)
            this.recursionTree(this.data3)
          })
      },

      // 递归菜单树
      recursionTree(arr, ids) {
        if (ids) {
          arr.forEach((item) => {
            if (ids.includes(Number(item.id))) {
              this.$set(item, 'checked', true)
            } else {
              this.$set(item, 'checked', false)
            }
            if (item.children && item.children.length > 0) {
              this.recursionTree(item.children, ids)
            }
          })
        } else {
          arr.forEach((item) => {
            this.$set(item, 'checked', false)
            if (item.children && item.children.length > 0) {
              this.recursionTree(item.children)
            }
          })
        }
      },
    },
    created() {
      this.$nextTick(function() {
        this.onresizeHeight =
          window.innerHeight - this.$refs.TableHeight.offsetTop - 50
      })
      this.getPermissionMenuList()
      this.getFunctionMenuList()
    },
  }
</script>
<style lang='scss' scoped>
  .functionalAuthority {
    padding: 20px;

    .topBox {
      height: 50px;

      .treeMenuRight {
        line-height: 32px;

        .menuCurr {
          display: flex;
          flex-direction: row;

          p {
            margin-right: 15px;

            span:first-child {
              display: inline-block;
              text-align: right;
            }
          }

          .menuBtn {
            >* {
              margin-left: 10px;
            }
          }
        }
      }
    }

    .topBox.hid {
      visibility: hidden;
    }

    .treeMenuLeft {
      position: relative;
    }
  }

  ::v-deep .ivu-row {
    height: 100%;
    overflow: hidden;

    .ivu-col {
      overflow-y: auto;
      height: 100%;
    }
  }
</style>